﻿using DapperDB.Entities;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace TaskSchedul
{
    public class Main
    {
        static ISchedulerFactory schedFact = new StdSchedulerFactory();
        private static IScheduler scheduler = schedFact.GetScheduler();

        /// <summary>
        /// 初始化
        /// </summary>
        public void Init()
        {
            scheduler.Start();
            RabbitMqHelper.ReceiveMessages();
        }


        /// <summary>
        /// web命令消息处理
        /// </summary>
        public static void MessageProcessing(string msg)
        {
            var msgModel = ToolHelper.ParseFromJson<MsgModel>(msg);

            var job = new Task_JobDap().GetByKey(msgModel.TaskID);

            JobModel JobKey = new JobModel();
            JobKey.TaskID = job.ID;
            JobKey.Name = job.Job_Name;
            JobKey.Group = job.Job_Group;
            JobKey.TriggerName = job.Trigger_Name;
            JobKey.TriggerGroup = job.Trigger_Group;
            JobKey.Cron = job.SetUpTime;

            //Operation 1 运行  2 删除 3 查询更新状态

            switch (msgModel.Operation)
            {
                case 1:
                    RunJob(JobKey);
                    break;
                case 2:
                    DeleteJob(JobKey);
                    break;
                case 3:
                    GetJobState(job);
                    break;
            }


        }


        /// <summary>
        /// 获取服务状态
        /// </summary>
        /// <param name="JobKey"></param>
        /// <returns></returns>
        public static void GetJobState(Task_Job Job)
        {
            try
            {

                TriggerKey tk = new TriggerKey(Job.Trigger_Name, Job.Trigger_Group);

                TriggerState state = scheduler.GetTriggerState(tk);

                //state的值代表该任务触发器的状态：
                //STATE_BLOCKED   4   阻塞
                //STATE_COMPLETE  2   完成
                //STATE_ERROR     3   错误
                //STATE_NONE    - 1   不存在
                //STATE_NORMAL    0  正常
                //STATE_PAUSED    1  暂停

                Job.Job_State = (int)Enum.Parse(typeof(TriggerState), state.ToString());

                new Task_JobDap().Update(Job);

            }
            catch (Exception ex)
            {
                ToolHelper.WriteLog("获取服务状态 TaskID:" + Job.ID, ex.ToString());
            }

        }

        /// <summary>
        /// 运行任务
        /// </summary>
        /// <param name="JobKey"></param>
        public static void RunJob(JobModel JobKey)
        {
            try
            {
                DeleteJob(JobKey);

                IJobDetail job = JobBuilder.Create<Run>()
                   .WithIdentity(JobKey.Name, JobKey.Group)
                   .UsingJobData("TaskID", JobKey.TaskID)
                   .Build();

                ITrigger trigger = TriggerBuilder.Create()
                 .WithIdentity(JobKey.TriggerName, JobKey.TriggerGroup)
                 .StartNow()
                  .WithCronSchedule(JobKey.Cron)
                 .Build();

                scheduler.ScheduleJob(job, trigger);

            }
            catch (Exception ex)
            {
                ToolHelper.WriteLog("运行任务 TaskID:" + JobKey.TaskID, ex.ToString());
            }

        }

        /// <summary>
        /// 暂停任务
        /// </summary>
        /// <param name="JobKey"></param>
        public bool PauseJob(JobModel JobKey)
        {
            try
            {
                JobKey jk = new JobKey(JobKey.Name, JobKey.Group);
                if (scheduler.CheckExists(jk))
                {
                    scheduler.PauseJob(jk);
                }
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 继续任务
        /// </summary>
        /// <param name="JobKey"></param>
        public bool ResumeJob(JobModel JobKey)
        {

            try
            {
                JobKey jk = new JobKey(JobKey.Name, JobKey.Group);
                if (scheduler.CheckExists(jk))
                {
                    scheduler.ResumeJob(jk);
                }
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;

        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="JobKey"></param>
        public static void DeleteJob(JobModel JobKey)
        {

            try
            {
                JobKey jk = new JobKey(JobKey.Name, JobKey.Group);
                if (scheduler.CheckExists(jk))
                {
                    scheduler.DeleteJob(jk);

                    new Task_JobDap().Delete(JobKey.TaskID);
                }
            }
            catch (Exception ex)
            {
                ToolHelper.WriteLog("删除任务 TaskID:"+ JobKey.TaskID, ex.ToString());
            }


        }

    }
}
